package com.zk.stock.service.serviceimpl;

import cn.hutool.http.server.HttpServerResponse;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zk.stock.mapper.StockMarketIndexInfoMapper;
import com.zk.stock.mapper.StockRtInfoMapper;
import com.zk.stock.pojo.domain.*;
import com.zk.stock.pojo.vo.StockInfoConfig;
import com.zk.stock.service.StockService;
import com.zk.stock.utils.DateTimeUtil;
import com.zk.stock.vo.resp.PageResult;
import com.zk.stock.vo.resp.R;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author 曹自康的Laptop
 * @version 1.0
 * @Date 2024-06-3018:15
 */
@Service
@RequiredArgsConstructor
public class StockServiceImpl implements StockService {
    private final StockInfoConfig stockInfoConfig;
    private final StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    private final StockRtInfoMapper stockRtInfoMapper;
    @Override
    public R<List<InnerMarketDomain>> getInnerMarket() {
        // 1.获取股票最新的交易时间点（精确到分钟，秒和毫秒置为0）
        Date curDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        // mock data 等后续完成股票采集job工程，再将代码删除即可
        curDate = DateTime.parse("2021-12-28 09:31:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

        // 2.获取大盘编码的集合
        List<String> mCodes = stockInfoConfig.getInner();

        // 3.调用mapper查询数据
      List<InnerMarketDomain> data = stockMarketIndexInfoMapper.getMarkeInfo(curDate,mCodes);

        // 4.封装并响应
        return R.ok(data);
    }

    @Override
    public R<List<StockBlockDomain>> getStockBlockAll() {
       List<StockBlockDomain> stockBlockDomainslist= stockMarketIndexInfoMapper.getStockBlockAll();
        return R.ok(stockBlockDomainslist) ;
    }

    @Override
    public R<PageResult<StockUpdownDomain>> getStockInfoByPage(Integer page, Integer pageSize) {
        // 1.获取股票最新的交易时间点（精确到分钟，秒和毫秒置为0）
        Date curDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
        // mock data 等后续完成股票采集job工程，再将代码删除即可
        curDate = DateTime.parse("2021-12-30 09:42:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();

        PageHelper.startPage(page,pageSize);
        List<StockUpdownDomain> pageData= stockRtInfoMapper.getStockInfoByTime(curDate);

        PageInfo<StockUpdownDomain> stockUpdownDomainPageInfo = new PageInfo<>(pageData);
        PageResult<StockUpdownDomain> stockUpdownDomainPageResult = new PageResult<>(stockUpdownDomainPageInfo);

        return R.ok(stockUpdownDomainPageResult);
    }

    @Override
    public List<StockUpdownDomain> stockUpdownDomainList() {
        List<StockUpdownDomain> stockLits =  stockRtInfoMapper.stockUpdownDomainList();
        return stockLits;
    }

    @Override
    public R<Map<String, List>> getStockUpDownCount() {
//        // 1.获取最新股票的交易时间点（截止的时间）
//        // 1.获取股票最新的交易时间点（精确到分钟，秒和毫秒置为0）
//        Date cuDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
//        // mock data 等后续完成股票采集job工程，再将代码删除即可
//        cuDate = DateTime.parse("2021-12-30 15:00:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
//
        // 1.获取最新股票的交易时间点（截至时间）
        DateTime curDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        curDateTime = DateTime.parse("2021-12-30 15:00:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date endDate = curDateTime.toDate();
        // 2.获取最新交易时间点对应的开盘时间点
        Date startDate = DateTimeUtil.getOpenDate(curDateTime).toDate();
        // 3.统计涨停
        List<Map> upList= stockRtInfoMapper.getStockUpDownCount(startDate,endDate,1);

        // 4.统计跌停
        List<Map> downList= stockRtInfoMapper.getStockUpDownCount(startDate,endDate,1);
        // 5.组装数据
        HashMap<String, List> info = new HashMap<>();
        info.put("upList",upList);
        info.put("downList",downList);
        return R.ok(info);
    }



    /**
     * 导出指定页码的最新股票信息
     *
     * @param page
     * @param pageSize
     * @param response
     */
    @Override
    public void exportStockUpDownInfo(Integer page, Integer pageSize, HttpServletResponse response) {
        // 1.获取分页数据
        R<PageResult<StockUpdownDomain>> stockInfoByPage = this.getStockInfoByPage(page, pageSize);
        List<StockUpdownDomain> rows = stockInfoByPage.getData().getRows();
        // 2.将数据导出excel中
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            String fileName = URLEncoder.encode("最新股票信息表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), StockUpdownDomain.class).sheet("股票涨幅信息").doWrite(rows);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public R<Map<String, List>> getStockTradeAmt() {
        // 1.获取T日最新股票交易的日期范围
        DateTime tEndDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        tEndDateTime =DateTime.parse("2021-12-29 14:40:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date tEndDate = tEndDateTime.toDate();
        // 开盘时间
        Date tStartDate = DateTimeUtil.getOpenDate(tEndDateTime).toDate();
        // 2.获取T-1日的时间范围
        DateTime preTEndDateTime = DateTimeUtil.getPreviousTradingDay(tEndDateTime);
        preTEndDateTime = DateTime.parse("2021-12-28 14:40:00", DateTimeFormat.forPattern("yy yy-MM-dd HH:mm:ss"));
        Date preTEndDate = preTEndDateTime.toDate();
        // 开盘时间
        Date tPreStartDate = DateTimeUtil.getOpenDate(preTEndDateTime).toDate();
      List<Map> tData =  stockMarketIndexInfoMapper.getSumAmtInfo(tStartDate,tEndDate,stockInfoConfig.getInner());
        System.out.println("tData = " + tData);
        List<Map> PreTData =  stockMarketIndexInfoMapper.getSumAmtInfo(tPreStartDate,preTEndDate,stockInfoConfig.getInner());
        System.out.println("PreTData = " + PreTData);

        // 组装数据
        HashMap<String, List> info = new HashMap<>();
        info.put("amtList",tData);
        info.put("yesAmtList",PreTData);



        return R.ok(info);
    }

    /**
     * 统计最新交易时间点下股票A股在各个涨幅区间的数量
     * @return
     */

    @Override
    public R<Map> getIncreaseRangeInfo() {
        // 1.获取当前最新的股票交易时间点
        DateTime curDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        curDateTime =DateTime.parse("2021-12-30 14:40:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date tEndDate = curDateTime.toDate();
        // 2.调用mapper获取数据
      List<Map> infos= stockRtInfoMapper.getIncreaseRangeInfos(tEndDate);
      // 获取有序的涨幅区间标题集合
        List<String> upDownRange = stockInfoConfig.getUpDownRange();
        System.out.println("upDownRange = " + upDownRange);

        // 将顺序的涨幅区间内的每个元素转化成Map对象即可
        List<Map> allInfos = new ArrayList<>();
        // 方式一：
        for (String title : upDownRange) {
            Map tmp = null;
            for (Map info : infos) {
                if (info.containsValue(title)) {
                    tmp =info;
                    break;

                }
            }
            if (tmp==null) {
                // 不存在则手动不起
                tmp = new HashMap();
                tmp.put("count",0);
                tmp.put("title",title);
            }
            allInfos.add(tmp);
        }

// 3.组装数据
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("time", LocalDateTime.now().toString());
//        stringObjectHashMap.put("infos",infos);
        stringObjectHashMap.put("infos",allInfos);

        // 4.响应
        return R.ok(stringObjectHashMap);
    }

    @Override
    public R<List<Stock4MinuteDomain>> getScreenTimeSharing(String code) {

        // 1.获取当前最新的股票交易时间点
        DateTime startDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        startDateTime =DateTime.parse("2021-12-30 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date startDate = startDateTime.toDate();
        /// 2.获取当的股票的结束时间
        DateTime endDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        endDateTime =DateTime.parse("2021-12-30 14:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date endDate = endDateTime.toDate();

       List<Stock4MinuteDomain> stock4MinuteDomainList= stockRtInfoMapper.getScreenTimeSharing(code,startDate,endDate);



        return R.ok(stock4MinuteDomainList);
    }

    @Override
    public R<List<Stock4EvrDayDomain>> getScreenDkline(String code) {
        // 1.获取当前最新的股票交易时间点
        DateTime startDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        startDateTime =DateTime.parse("2021-12-20 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date startDate = startDateTime.toDate();

        /// 2.获取当的股票的结束时间
        DateTime endDateTime = DateTimeUtil.getLastDate4Stock(DateTime.now());
        // 假数据
        endDateTime =DateTime.parse("2021-12-30 14:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        Date endDate = endDateTime.toDate();
        List<Stock4EvrDayDomain> stock4EvrDayDomainList =   stockRtInfoMapper.getScreenDkline(code,startDate,endDate);
        return R.ok(stock4EvrDayDomainList);
    }


}
